package cn.edu.neusoft.demo.hospital2.Controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/ai")
@CrossOrigin(origins = "*")
public class AiController {

    private final RestTemplate restTemplate;
    private final ObjectMapper objectMapper;  // 自动注入 Jackson 的 ObjectMapper

    public AiController(RestTemplate restTemplate, ObjectMapper objectMapper) {
        this.restTemplate = restTemplate;
        this.objectMapper = objectMapper;
    }

    @PostMapping("/chat")
    public ResponseEntity<String> chatWithAI(@RequestBody String userMessage) throws JsonProcessingException {
        // 先检查消息是否与医学有关
        if (!isMedicalRelatedByAI(userMessage)) {
            return ResponseEntity.badRequest().body("抱歉，我只能回答与医学相关的问题，请重新提问。");
        }

        String url = "https://api.deepseek.com/v1/chat/completions";

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "Bearer sk-e60695c75c494e81a04c84656cbda0af");

        // 使用 Map 构建请求体（自动处理 JSON 转义）
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("model", "deepseek-chat");
        requestBody.put("stream", false);

        List<Map<String, String>> messages = new ArrayList<>();
        messages.add(Map.of("role", "user", "content", userMessage));
        requestBody.put("messages", messages);

        String jsonBody = objectMapper.writeValueAsString(requestBody);  // 自动转义特殊字符

        HttpEntity<String> entity = new HttpEntity<>(jsonBody, headers);

        ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);
        return ResponseEntity.ok(response.getBody());
    }

    // 新增方法：通过调用AI模型判断问题是否与医学相关
    private boolean isMedicalRelatedByAI(String text) throws JsonProcessingException {
        String url = "https://api.deepseek.com/v1/chat/completions";

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "Bearer sk-e60695c75c494e81a04c84656cbda0af");

        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("model", "deepseek-chat");
        requestBody.put("stream", false);

        String classificationPrompt = "请判断以下内容是否涉及医学、医疗、健康或疾病相关的话题。如果是，请回复'是'，否则回复'否':\n\n" + text;

        List<Map<String, String>> messages = new ArrayList<>();
        messages.add(Map.of("role", "user", "content", classificationPrompt));
        requestBody.put("messages", messages);

        String jsonBody = objectMapper.writeValueAsString(requestBody);

        HttpEntity<String> entity = new HttpEntity<>(jsonBody, headers);

        ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);
        String responseBody = response.getBody();

        // 解析AI返回的结果
        if (responseBody != null) {
            // 假设返回的是JSON格式，并且包含choices数组和content字段
            // 这里需要根据实际API响应结构调整解析逻辑
            // 简化处理，直接检查响应中是否有“是”
            return responseBody.contains("\"content\":\"是\"") || responseBody.contains("是");
        }

        return false;
    }
}